package rs.etf.kdp.server;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

import rs.etf.kdp.client.Job;

/**
 * Keeps data about one simulation
 * @author Djordje Vukovic
 * @version 1.0
 * @created 20-May-2011 2:30:16 AM
 */
public class Simulation {

	private Job job;
	private List<Node> simulatingOn;
	private AvailableNodes availableNodes;
	private String simulationStatus;
	private JobManager manager;
	private Result results;
	
	public Simulation(Job j, AvailableNodes an, List<Node> simulatingOnNodes, JobManager m)
	{
		job = j;
		availableNodes = an;
		simulatingOn = simulatingOnNodes;
		simulationStatus = "SCHEDULED";
		manager = m;
	}
	
	public void abortThisSimulation()//only send messages to the workstations
	{
		for(Node n : simulatingOn)
		{
			ObjectOutputStream out = n.getOutput();
			try {
				out.writeObject("abort " + job.getServerID());
			} catch (IOException e) {
				System.out.println("Unable to send abort messages");
				return;
			}
		}
		simulationStatus = "ABORTED";
		// check what happens if here is checked aborted
		//need to interrupt job manager
	}
	
	public void requestResults()
	{
		for(Node n : simulatingOn)
		{
			ObjectOutputStream out = n.getOutput();
			try {
				out.writeObject("request " + job.getServerID());
			} catch (IOException e) {
				System.out.println("Unable to send request result messages");
				return;
			}
		}
	}

	
	public void restartThisSimulation(CurrentSimulations cs)
	{
		if(simulationStatus.equals("DONE")) return;
		JobManager newJM = new JobManager(manager.getJob(), manager.getStatus(), manager.getInputToClient(), manager.getOutputToClient(), manager.getHb());
		abortThisSimulation();
		manager.interrupt();
		cs.removeActiveSimulation(job.getServerID());
		NewConnectionsListener.jobManagerPool.submit(newJM);
		
	}
	
	public Job getJob() {
		return job;
	}

	public void setJob(Job job) {
		this.job = job;
	}

	public List<Node> getSimulatingOn() {
		return simulatingOn;
	}

	public void setSimulatingOn(List<Node> simulatingOn) {
		this.simulatingOn = simulatingOn;
	}

	public AvailableNodes getAvailableNodes() {
		return availableNodes;
	}

	public void setAvailableNodes(AvailableNodes availableNodes) {
		this.availableNodes = availableNodes;
	}

	public String getSimulationStatus() {
		return simulationStatus;
	}

	public void setSimulationStatus(String simulationStatus) {
		this.simulationStatus = simulationStatus;
	}

	public JobManager getManager() {
		return manager;
	}

	public void setManager(JobManager manager) {
		this.manager = manager;
	}
	
	
	public void addSimulatingOn(Node n)
	{
		simulatingOn.add(n);
	}

	public Result getResults() {
		return results;
	}

	public void setResults(Result results) {
		this.results = results;
	}
	
	

}